import SYCM from "~/utils/ali/sycm";
import Trans from "~/utils/sycm/trans";

export interface SycmAnalysisFlowRow {
    pageId: string;
    pPageId: string;
    pageName: string;
    pageName1: string;
    pageName2: string | null;
    pageName3: string | null;
    pageLevel: number;
    PayAmt: { cycleCrc?: number; value?: number };
    PayByrCnt: { cycleCrc?: number; value?: number };
    PayByrCntIndex: { cycleCrc?: number; ratio?: number; syncCrc?: number; value?: number };
    PayRate: { cycleCrc?: number; value?: number };
    PayRateIndex: { cycleCrc?: number; ratio?: number; syncCrc?: number; value?: number };
    TradeIndex: { cycleCrc?: number; ratio?: number; syncCrc?: number; value?: number };
    Uv: { cycleCrc?: number; value?: number };
    UvIndex: { cycleCrc?: number; ratio?: number; syncCrc?: number; value?: number };
    showDesc: boolean;
    uvValue: string;
    customerPrice: string;
}

export interface Shop {
    title: string;
    logo: string;
    shopId: number;
    b2CShop: boolean;
    ShopTrend?: ShopTrend;
    TopTable?: any;
    CateTradeData?: any;
    PriceTradeData?: any;
    FlowTableData?: SycmAnalysisFlowRow[];
}

// 竞店指标统计信息
export interface ShopTrend {
    CartHits: any[];
    CltHits: any[];
    FstOnsItmCnt: any[];
    IpvUv: any[];
    PayByrCntIndex: any[];
    PayRateIndex: any[];
    PrePayAmtIndex: any[];
    PrePayItmCnt: any[];
    SeIpvUvHits: any[];
    TradeIndex: any[];
    UserId: any[];
    UvIndex: any[];
    // 访客数
    uv: any[];
    // 客单价
    CustomerPrice: any[];
    // UV价值
    UVValue: any[];
    // 搜索占比
    SeIpvUvHitsRate: any[];
    // 收藏率
    CltHitsRate: any[];
    // 加购率
    CartHitsRate: any[];
    // 收藏加购率
    CltCartHitsRate: any[];
}

export interface ShopLists {
    // 本店信息
    selfShop: Shop | null;
    // 竞店1
    shop1: Shop | null;
    // 竞店2
    shop2: Shop | null;
}

export class SycmShopAnalysisSale {
    static async getDates(): Promise<string[]> {
        const data = await SYCM.getInternalFiberData('[id^=sycm-mc-ci-index-compare] > div.oui-card-content.alife-one-design-sycm-indexes-trend-card-content > div > div.alife-one-design-sycm-indexes-trend-chart-container.alife-one-design-sycm-indexes-trend-chart-container-tradeIndex > div > div > div', 'alternate.memoizedProps.children.props.children.props.data');
        return data.map((item: any) => {
            return item.fullDate;
        });
    }

    // 获取店铺信息 获取对比店铺信息
    static async getShops(): Promise<ShopLists> {
        let data = await SYCM.getInternalFiberData('[id^=__qiankun_microapp_wrapper_for_op_mc] > div > div > div > div > div:nth-child(1) > div', 'memoizedProps.children[0]._owner.memoizedProps');
        const selfShop: Shop = {
            title: data.selfShopInfo.runAsUserName,
            logo: data.selfShopInfo.runAsUserImg,
            shopId: data.selfShopInfo.runAsUserId,
            b2CShop: data.selfShopInfo.b2CShop || false,
        };
        let shop1: Shop | null = null;
        if (data.rivalShop1 && typeof data.rivalShop1.shop!== 'undefined' && data.rivalShop1.shop) {
            shop1 = {
                title: data.rivalShop1.shop.name,
                logo: data.rivalShop1.shop.picUrl,
                shopId: data.rivalShop1.shop.shopId,
                b2CShop: data.rivalShop1.shop.b2CShop,
            };
        }
        let shop2: Shop | null = null;
        if (data.rivalShop2 && typeof data.rivalShop2.shop!== 'undefined' && data.rivalShop2.shop) {
            shop2 = {
                title: data.rivalShop2.shop.name,
                logo: data.rivalShop2.shop.picUrl,
                shopId: data.rivalShop2.shop.shopId,
                b2CShop: data.rivalShop2.shop.b2CShop,
            };
        }
        return {
            selfShop,
            shop1,
            shop2,
        };
    }

    // 注入交易构成 类目交易构成
    static async assignShopCateTradeData(shopLists: ShopLists,retry:number = 0): Promise<ShopLists|null> {
        if (retry > 5) {
            return null;
        }
        const data = await SYCM.getInternalFiberData('[id^=sycm-mc-ci-index-compare] > div.oui-card-content.alife-one-design-sycm-indexes-trend-card-content', 'memoizedProps.children._owner.memoizedProps.context.storeState[\'sycm-mc-shop-analyse\'][\'sycm-mc-shop-analysis-sale\']');
        if (typeof data['sycm-mc-shop-analysis-sale-trade-cate-selfUserId'] === 'undefined' || !data['sycm-mc-shop-analysis-sale-trade-price-selfUserId']) {
            return new Promise((resolve, reject) => {
                setTimeout(() => {
                    resolve(this.assignShopCateTradeData(shopLists,retry + 1));
                }, 1000);
            });
        }
        if (typeof data['sycm-mc-shop-analysis-sale-trade-price-selfUserId'] === 'undefined' || !data['sycm-mc-shop-analysis-sale-trade-price-selfUserId']) {
            return new Promise((resolve, reject) => {
                setTimeout(() => {
                    resolve(this.assignShopCateTradeData(shopLists,retry + 1));
                }, 1000);
            });
        }
        if (shopLists.selfShop) {
            shopLists.selfShop = await this.assignShopCateTrade(shopLists.selfShop, 0, data);
        }
        if (shopLists.shop1) {
            shopLists.shop1 = await this.assignShopCateTrade(shopLists.shop1, 1, data);
        }
        if (shopLists.shop2) {
            shopLists.shop2 = await this.assignShopCateTrade(shopLists.shop2, 2, data);
        }
        return shopLists;
    }

    private static async assignShopCateTrade(shop: Shop, shopType: number, data: any): Promise<Shop> {
        let keyPrefix = '';
        switch (shopType) {
            case 0:
                keyPrefix = 'selfUserId';
                break;
            case 1:
                keyPrefix = 'rivalUser1Id';
                break;
            case 2:
                keyPrefix = 'rivalUser2Id';
                break;
        }
        // 类目构成
        shop.CateTradeData = data['sycm-mc-shop-analysis-sale-trade-cate-' + keyPrefix].cateData.data;
        // 价格带
        if (typeof data['sycm-mc-shop-analysis-sale-trade-price-' + keyPrefix] === 'undefined') {
            return new Promise((resolve, reject) => {
                setTimeout(() => {
                    resolve(this.assignShopCateTrade(shop, shopType, data));
                }, 1000);
            });
        } else {
            shop.PriceTradeData = data['sycm-mc-shop-analysis-sale-trade-price-' + keyPrefix].priceData.data;
        }
        return shop;
    }

    // 获取店铺指标统计信息
    static async assignShopListTrend(shopLists: ShopLists): Promise<ShopLists> {
        const data = await SYCM.getInternalFiberData('[id^=sycm-mc-ci-index-compare] > div.oui-card-content.alife-one-design-sycm-indexes-trend-card-content', 'memoizedProps.children._owner.memoizedProps');
        if (shopLists.selfShop) {
            shopLists.selfShop = this.assignShopTrend(shopLists.selfShop, 0, data);
        }
        if (shopLists.shop1) {
            shopLists.shop1 = this.assignShopTrend(shopLists.shop1, 1, data);
        }
        if (shopLists.shop2) {
            shopLists.shop2 = this.assignShopTrend(shopLists.shop2, 2, data);
        }
        return shopLists;
    }

    // 获取店铺指标统计信息
    private static assignShopTrend(shop: Shop, shopType: number, data: any): Shop {
        let keyPrefix = '';
        switch (shopType) {
            case 0:
                keyPrefix = 'selfShop';
                break;
            case 1:
                keyPrefix = 'rivalShop1';
                break;
            case 2:
                keyPrefix = 'rivalShop2';
                break;
        }
        shop.ShopTrend = {
            CartHits: data.trendData.data[keyPrefix + 'CartHits'],
            CltHits: data.trendData.data[keyPrefix + 'CltHits'],
            FstOnsItmCnt: data.trendData.data[keyPrefix + 'FstOnsItmCnt'],
            IpvUv: data.trendData.data[keyPrefix + 'IpvUv'],
            PayByrCntIndex: data.trendData.data[keyPrefix + 'PayByrCntIndex'],
            PayRateIndex: data.trendData.data[keyPrefix + 'PayRateIndex'],
            PrePayAmtIndex: data.trendData.data[keyPrefix + 'PrePayAmtIndex'],
            PrePayItmCnt: data.trendData.data[keyPrefix + 'PrePayItmCnt'],
            SeIpvUvHits: data.trendData.data[keyPrefix + 'SeIpvUvHits'],
            TradeIndex: data.trendData.data[keyPrefix + 'TradeIndex'],
            UserId: data.trendData.data[keyPrefix + 'UserId'],
            UvIndex: data.trendData.data[keyPrefix + 'UvIndex'],
            uv: data.trendData.data[keyPrefix + 'UvIndex'].map((item: number | string) => {
                if (item === null) {
                    return null;
                }
                if (!item) {
                    return 0;
                }
                return Trans.number(item).toFixed(2);
            }),
            CustomerPrice: data.trendData.data[keyPrefix + 'TradeIndex'].map((item: any, index: number) => {
                if (item === null) {
                    return null;
                }
                const price = (Trans.number(item) / Trans.number(data.trendData.data[keyPrefix + 'PayByrCntIndex'][index])).toFixed(2);
                if (price === 'NaN') {
                    return '0.00';
                }
                return price;
            }),
            UVValue: data.trendData.data[keyPrefix + 'TradeIndex'].map((item: any, index: number) => {
                if (item === null) {
                    return null;
                }
                const uv = (Trans.number(item) / Trans.number(data.trendData.data[keyPrefix + 'UvIndex'][index])).toFixed(2);
                if (uv === 'NaN') {
                    return '0.00';
                }
                return uv;
            }),
            SeIpvUvHitsRate: data.trendData.data[keyPrefix + 'SeIpvUvHits'].map((item: any, index: number) => {
                if (item === null) {
                    return null;
                } else {
                    if (item) {
                        return (Trans.number(item) / Trans.number(data.trendData.data[keyPrefix + 'UvIndex'][index])).toFixed(4);
                    } else {
                        return 0.00;
                    }
                }
            }),
            CltHitsRate: data.trendData.data[keyPrefix + 'CltHits'].map((item: any, index: number) => {
                if (item === null) {
                    return null;
                } else {
                    if (item) {
                        return (Trans.number(item) / Trans.number(data.trendData.data[keyPrefix + 'UvIndex'][index])).toFixed(4);
                    } else {
                        return 0.00;
                    }
                }
            }),
            CartHitsRate: data.trendData.data[keyPrefix + 'CartHits'].map((item: any, index: number) => {
                if (item === null) {
                    return null;
                } else {
                    if (item) {
                        return (Trans.number(item) / Trans.number(data.trendData.data[keyPrefix + 'UvIndex'][index])).toFixed(4);
                    } else {
                        return 0.00;
                    }
                }
            }),
            CltCartHitsRate: data.trendData.data[keyPrefix + 'CltHits'].map((item: any, index: number) => {
                if (item === null) {
                    return null;
                } else {
                    if (item && data.trendData.data[keyPrefix + 'CartHits'][index]) {
                        return (Trans.number(item + data.trendData.data[keyPrefix + 'CartHits'][index]) / Trans.number(data.trendData.data[keyPrefix + 'UvIndex'][index])).toFixed(4);
                    } else {
                        return 0.00;
                    }
                }
            }),
        }
        return shop;
    }

    // 获取竞店流量分析
    static async assignShopListFlowTable(shopLists: ShopLists): Promise<ShopLists> {
        const data = await SYCM.getInternalFiberData('#sycm-mc-shop-analysis-flow-source-new > div.oui-card-content > div.oui-table-wrapper > div', 'memoizedProps.children._owner.memoizedProps.dataSource[0]');
        if (typeof data === 'undefined' || !data) {
            return new Promise((resolve, reject) => {
                setTimeout(() => {
                    resolve(this.assignShopListFlowTable(shopLists));
                }, 1000);
            });
        }
        if (shopLists.selfShop) {
            shopLists.selfShop = await this.assignShopFlowTable(shopLists.selfShop, 0, data);
        }
        if (shopLists.shop1) {
            shopLists.shop1 = await this.assignShopFlowTable(shopLists.shop1, 1, data);
        }
        if (shopLists.shop2) {
            shopLists.shop2 = await this.assignShopFlowTable(shopLists.shop2, 2, data);
        }
        return shopLists;
    }

    private static async assignShopFlowTable(shop: Shop, type: number, data: any, indexes: number[] = [], pageNames: string[] = []): Promise<Shop> {
        let keyPrefix = '';
        switch (type) {
            case 0:
                keyPrefix = 'selfShop';
                break;
            case 1:
                keyPrefix = 'rivalShop1';
                break;
            case 2:
                keyPrefix = 'rivalShop2';
                break;
        }

        let d: any;
        if (indexes.length === 0) {
            d = JSON.parse(JSON.stringify(data));
        } else if (indexes.length === 1) {
            d = JSON.parse(JSON.stringify(data.children[indexes[0]]));
        } else if (indexes.length === 2) {
            d = JSON.parse(JSON.stringify(data.children[indexes[0]].children[indexes[1]]));
        } else if (indexes.length === 3) {
            d = JSON.parse(JSON.stringify(data.children[indexes[0]].children[indexes[1]].children[indexes[2]]));
        }
        if (typeof shop.FlowTableData === 'undefined') {
            shop.FlowTableData = [];
        }
        pageNames.push(d.pageName.value);
        let customerPrice = '0.00';
        if (typeof d[keyPrefix + 'TradeIndex'] !== 'undefined' && typeof d[keyPrefix + 'TradeIndex'].value !== 'undefined' &&
            typeof d[keyPrefix + 'PayByrCntIndex'] !== 'undefined' && typeof d[keyPrefix + 'PayByrCntIndex'].value !== 'undefined') {
            customerPrice = (Trans.number(d[keyPrefix + 'TradeIndex'].value) / Trans.number(d[keyPrefix + 'PayByrCntIndex'].value || 0)).toFixed(2);
            if (customerPrice === 'NaN') {
                customerPrice = '0.00';
            }
        }
        let uvValue = '0.00';
        if (typeof d[keyPrefix + 'TradeIndex'] !== 'undefined' && typeof d[keyPrefix + 'TradeIndex'].value !== 'undefined' &&
            typeof typeof d[keyPrefix + 'UvIndex'] !== 'undefined' && typeof d[keyPrefix + 'UvIndex'].value !== 'undefined') {
            uvValue = (Trans.number((d[keyPrefix + 'TradeIndex'].value || 0)) / Trans.number(d[keyPrefix + 'UvIndex'].value || 0)).toFixed(2);
            if (uvValue === 'NaN') {
                uvValue = '0.00';
            }
        }
        shop.FlowTableData.push({
            pageName1: pageNames[0],
            pageName2: pageNames[1] || null,
            pageName3: pageNames[2] || null,
            PayAmt: {...d[keyPrefix + 'PayAmt']},
            PayByrCnt: {...d[keyPrefix + 'PayByrCnt']},
            PayByrCntIndex: {...d[keyPrefix + 'PayByrCntIndex']},
            PayRate: {...d[keyPrefix + 'PayRate']},
            PayRateIndex: {...d[keyPrefix + 'PayRateIndex']},
            TradeIndex: {...d[keyPrefix + 'TradeIndex']},
            Uv: {...d[keyPrefix + 'Uv']},
            UvIndex: {...d[keyPrefix + 'UvIndex']},
            pageLevel: indexes.length,
            pageName: d.pageName.value,
            showDesc: d.showDesc.value === 1,
            pageId: d.pageId.value,
            pPageId: d.pPageId.value,
            customerPrice: customerPrice,
            uvValue: uvValue,
        });

        if (typeof d.children !== 'undefined') {
            for (const item of d.children) {
                const index: number = d.children.indexOf(item);
                shop = await this.assignShopFlowTable(shop, type, data, [...indexes, index], [...pageNames]);
            }
        }
        shop.TopTable = d;
        return shop;
    }

    // 获取竞店的top表格数据
    static async assignShopListTopTable(shopLists: ShopLists): Promise<ShopLists> {
        const data = await SYCM.getInternalFiberData('[id^=sycm-mc-ci-index-compare] > div.oui-card-content.alife-one-design-sycm-indexes-trend-card-content', 'memoizedProps.children._owner.memoizedProps.context.storeState[\'sycm-mc-shop-analyse\'][\'sycm-mc-shop-analysis-sale\']');
        if (typeof data['sycm-mc-shop-analysis-sale-trade-table-selfShop'] === 'undefined') {
            const dom = document.querySelector("#sycm-mc-shop-analysis-sale-top div.oui-card-header span.oui-tab-switch > span:nth-child(1)");
            if (dom) {
                (dom as HTMLElement).click();
            }
            return new Promise((resolve, reject) => {
                setTimeout(() => {
                    resolve(this.assignShopListTopTable(shopLists));
                }, 1000);
            });
        }
        if (typeof data['sycm-mc-shop-analysis-sale-flow-table-selfShop'] === 'undefined') {
            const dom = document.querySelector("#sycm-mc-shop-analysis-sale-top div.oui-card-header span.oui-tab-switch > span:nth-child(2)");
            if (dom) {
                (dom as HTMLElement).click();
            }
            return new Promise((resolve, reject) => {
                setTimeout(() => {
                    resolve(this.assignShopListTopTable(shopLists));
                }, 1000);
            });
        }
        if (shopLists.selfShop) {
            shopLists.selfShop = await this.assignShopTopTable(shopLists.selfShop, 0, data);
        }
        if (shopLists.shop1) {
            shopLists.shop1 = await this.assignShopTopTable(shopLists.shop1, 1, data);
        }
        if (shopLists.shop2) {
            shopLists.shop2 = await this.assignShopTopTable(shopLists.shop2, 2, data);
        }
        return shopLists;
    }

    private static async assignShopTopTable(shop: Shop, type: number, data: any): Promise<Shop> {
        let keyPrefix = '';
        switch (type) {
            case 0:
                keyPrefix = 'selfShop';
                break;
            case 1:
                keyPrefix = 'rivalShop1';
                break;
            case 2:
                keyPrefix = 'rivalShop2';
                break;
        }
        const d: any[] = [];
        const tradeTableData = data['sycm-mc-shop-analysis-sale-trade-table-' + keyPrefix].originalTableData.data.data;
        const flowTableData = data['sycm-mc-shop-analysis-sale-flow-table-' + keyPrefix].originalTableData.data.data;
        // 计算data 将tradeTableData flowTableData合并 根据item.detailUrl 判断是否是同一个商品 如果不存在则直接添加
        tradeTableData.forEach((item: any) => {
            const flowItem = flowTableData.find((flowItem: any) => {
                return flowItem.detailUrl === item.detailUrl;
            });
            if (flowItem) {
                d.push({
                    ...item,
                    ...flowItem,
                });
            } else {
                d.push(item);
            }
        });
        flowTableData.forEach((item: any) => {
            const tradeItem = d.find((tradeItem: any) => {
                return tradeItem.detailUrl === item.detailUrl;
            });
            if (!tradeItem) {
                d.push(item);
            }
        })
        shop.TopTable = d;
        return shop;
    }


}
